package com.wonders.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wonders.springboot.bean.Menu;
import com.wonders.springboot.bean.Role;
import com.wonders.springboot.bean.Users;
import com.wonders.springboot.mapper.UsersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper();
        wrapper.eq("username",username);
        Users users = usersMapper.selectOne(wrapper);
        if(users == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        log.info("查到的用户："+users);

        //给用户添加角色信息
        List<GrantedAuthority> auths = new ArrayList<>();
        List<Role> roles = usersMapper.selectRoleByUserId((long) users.getId());
        List<Menu> menus = usersMapper.selectMenuByUserId((long) users.getId());
        log.info("用户的角色信息："+roles);
        for (Role role : roles) {
            auths.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        for (Menu menu : menus) {
            auths.add(new SimpleGrantedAuthority(menu.getPermission()));
        }

        return new User(users.getUsername(), users.getPassword(),auths);
    }

}
